from django import forms
from .models import Author, Book
from .models import Review



class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['name', 'bio']


class BookForm(forms.ModelForm):
    # 将 author 字段覆盖为 CharField
    author_name = forms.CharField(label='Author', max_length=100)

    class Meta:
        model = Book
        fields = ['title', 'author_name']  # 只显示 title 和我们自定义的 author_name

    def save(self, commit=True):
        # 从表单中获取作者名字
        author_name = self.cleaned_data.get('author_name')
        # 查找或创建一个新的作者
        author, created = Author.objects.get_or_create(name=author_name)

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            if self.instance and self.instance.pk:
                # 如果是编辑现有书籍，将作者名字填充到 author_name 字段
                self.fields['author_name'].initial = self.instance.author.name

        # 将实例的 author 字段设置为我们找到或创建的作者
        self.instance.author = author

        # 调用父类的 save 方法保存 Book 实例
        return super().save(commit)
    author_name = forms.CharField(label='作者', max_length=100)
    description = forms.CharField(label='介绍', widget=forms.Textarea, required=False)  # 新增

    class Meta:
        model = Book
        fields = ['title', 'author_name', 'description']  # 加入 description

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk and self.instance.author:
            self.fields['author_name'].initial = self.instance.author.name
        if self.instance and self.instance.pk:
            self.fields['description'].initial = self.instance.description  # 新增

    def save(self, commit=True):
        author_name = self.cleaned_data.get('author_name')
        author, created = Author.objects.get_or_create(name=author_name)
        self.instance.author = author
        self.instance.description = self.cleaned_data.get('description')  # 新增
        return super().save(commit)

class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        fields = ['content']
        labels = {'content': '书评内容'}